package org.example.jnautil.key;


import basicutil.common.ThreadUtil;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class HookKeyHandler {
    public static final int KEY_NUMBER = 1024;

    final StatefulKeyListener[] keyListeners = new StatefulKeyListener[KEY_NUMBER];
    final StatelessListener[] statelessListeners = new StatelessListener[20];
    private final boolean[] keyTableState = new boolean[KEY_NUMBER];
    private final boolean[] unstashing = new boolean[KEY_NUMBER];
    int[] lastCode = {-1, -1};

    public boolean getKeyState(int code) {
        return keyTableState[code];
    }

    boolean acceptKey(int vkCode, boolean keyDown) {
        lastCode[0] = lastCode[1];
        lastCode[1] = vkCode;
        keyTableState[vkCode] = keyDown;
        // 程序自己触发的虚拟按键不能重复触发，否则会无限循环
        if (unstashing[vkCode]) {
            if (!keyDown) {
                unstashing[vkCode] = false;
                keyListeners[vkCode].onKeyEvent(this, keyDown);

            }
            return true;
        }

        for (StatelessListener listener : statelessListeners) {
            if (listener == null) {
                break;
            }
            ThreadUtil.runLaterSafely(() -> listener.onKeyEvent(vkCode, keyDown, keyTableState));
        }

        StatefulKeyListener listener = keyListeners[vkCode];
        if (listener != null) {
            ListenKeyResult listenKeyResult = listener.onKeyEvent(this, keyDown);
            if (listenKeyResult.shouldUnstash) {
                unstashing[vkCode] = true;
                KeyBoardManager.NativeKeySender.keyDown(vkCode);
                KeyBoardManager.NativeKeySender.keyUp(vkCode);
            }
            return listenKeyResult.shouldPass;
        } else {
            return true;
        }
    }
}
